package com.zf.shuashua;


import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.download.DownloadListener;
import com.tencent.bugly.beta.download.DownloadTask;
import com.zf.shuashua.base.BaseActivity;

public class UpgradeActivity extends BaseActivity implements DownloadListener {

    private Button start;

    private int isForce;

    @Override
    protected void initView() {
        //"弹窗类型（1:建议 2:强制 3:手工）: "
        isForce = getIntent().getIntExtra("upgradeType",-1);
        Beta.registerDownloadListener(this);
        start = findViewById(R.id.start_upgrade);
        TextView cancelUpgrade = findViewById(R.id.cancel_upgrade);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownloadTask task = Beta.startDownload();
                if(task==null){
                    return;
                }
                updateBtn(task);
                if (task.getStatus() == DownloadTask.DOWNLOADING) {
                    finish();
                }
            }
        });

        if(isForce==2){
            cancelUpgrade.setVisibility(View.INVISIBLE);
        }

        cancelUpgrade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Beta.cancelDownload();
                finish();
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_upgrade;
    }

    @Override
    public void onReceive(DownloadTask task) {
        updateBtn(task);
        start.setText(task.getSavedLength() + "");
    }

    @Override
    public void onCompleted(DownloadTask downloadTask) {

    }

    @Override
    public void onFailed(DownloadTask downloadTask, int i, String s) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Beta.unregisterDownloadListener();
    }

    public void updateBtn(DownloadTask task) {

        /*根据下载任务状态设置按钮*/
        switch (task.getStatus()) {
            case DownloadTask.INIT:
            case DownloadTask.DELETED:
            case DownloadTask.FAILED: {
                start.setText("开始下载");
            }
            break;
            case DownloadTask.COMPLETE: {
                start.setText("安装");
            }
            break;
            case DownloadTask.DOWNLOADING: {
                start.setText("暂停");
            }
            break;
            case DownloadTask.PAUSED: {
                start.setText("继续下载");
            }
            break;
        }
    }
}
